package android.main;

import java.io.BufferedReader;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.utility.Utility;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ProgressBar;
import com.example.piano_application.R;
/**
 * 시작 페이지 처리
 * 1. 관리자가 등록한 핸드폰 번호로 접속시 메인화면으로 이동
 * 2. 미동록 회원은 별도의 화면으로 처리할 예정
 * */
@SuppressLint("HandlerLeak")
public class Index extends Activity {

	private int mValue;
	private ProgressBar mProgress;
	private boolean mQuit;
	private ServerThread mThread;

	JSONObject memberobj = null;

	String phoneNumber = "";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.index);

		if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                    .permitAll().build();

            StrictMode.setThreadPolicy(policy);
        }
		
		TelephonyManager tel = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
		phoneNumber = tel.getLine1Number();

		mProgress = (ProgressBar) findViewById(R.id.index_pgb);
		mProgress.setVisibility(View.INVISIBLE);

		mValue = 0;
		mQuit = false;
		mThread = new ServerThread();
		mThread.start();
	}

	Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			mValue = msg.arg1;
			if (mValue == 4) {
				mProgress.setVisibility(View.VISIBLE);
			} else if (mValue == 5) {
				mQuit = true;
				
				StringBuilder html = new StringBuilder();
				try {
					String id = phoneNumber;
					String replace = null;
					replace = id.replace("+82", "01");
					if(replace != null){
						phoneNumber = replace;
					}
					// 현재 내 핸드폰번호를 받아와서 서버로 전송해주는 부분
					BufferedReader br = Utility.loadHTML(MemberConst.READ+"?id="+id);
					while (true) {
						String line = br.readLine();
						Log.d("D","line : " +line);
						if (line == null)
							break;
						html.append(line + '\n');
					}
					br.close();

					memberobj = new JSONObject(html.toString());

				} catch (Exception e) {
					Log.d("D", e.toString());
				}
				
				if(memberobj.length() > 2){
					Intent intent = null;
					intent = new Intent(getApplicationContext(), Main_menu.class);
					intent.putExtra("id", phoneNumber);
					startActivity(intent);
					finish();
				}else{
					Intent intent = null;
					intent = new Intent(getApplicationContext(), Main_menu.class);
					intent.putExtra("id", phoneNumber);
					startActivity(intent);
					finish();
				}
			}
		}
	};

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	class ServerThread extends Thread {
		public void run() {
			while (mQuit == false) {
				mValue++;

				Message msg = mHandler.obtainMessage();
				msg.arg1 = mValue;
				mHandler.sendMessage(msg);
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					;
				}
			}
		}
	}

}
